package com.example.admin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.SysUserRole;
import com.example.admin.mapper.SysUserMapper;
import com.example.admin.service.ISysUserRoleService;
import com.example.admin.service.ISysUserService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Resource(name = "sysUserRoleService")
	private ISysUserRoleService urSevice;

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean saveSysUser(SysUser sysUser) {
		if (sysUser.insert()) {
			if (sysUser.getId() != null) {
				List<SysRole> list = sysUser.getRoleList();
				for (SysRole sysRole : list) {
					SysUserRole userRole = new SysUserRole();
					userRole.setRoleId(sysRole.getId());
					userRole.setUserId(sysUser.getId());
					if (!userRole.insert()) {
						throw new RuntimeException();
					}
				}
			}
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean updateSysUser(SysUser sysUser) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.eq("user_id", sysUser.getId());
		if (urSevice.remove(queryWrapper)) {
			if (sysUser.insertOrUpdate()) {
				List<SysRole> list = sysUser.getRoleList();
				for (SysRole sysRole : list) {
					SysUserRole userRole = new SysUserRole();
					userRole.setRoleId(sysRole.getId());
					userRole.setUserId(sysUser.getId());
					if (!userRole.insert()) {
						throw new RuntimeException();
					}
				}
			} else {
				throw new RuntimeException();
			}
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean deleteSysUser(SysUser sysUser) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
		queryWrapper.eq("user_id", sysUser.getId());
		if (urSevice.remove(queryWrapper)) {
			if (!sysUser.deleteById()) {
				throw new RuntimeException();
			}
		}
		return true;
	}

}
